//
//  QGString.swift
//  B2BAutoziMall
//
//  Created by autozi01 on 16/3/8.
//  Copyright © 2016年 qeegoo. All rights reserved.
//

import UIKit

let kAlphaNum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
let pureNum = "0123456789"

public extension Character {
    
    /**
     If the character represents an integer that fits into an Int, returns
     the corresponding integer.
     */
    public func toInt () -> Int? {
        return Int(String(self))
    }
}

extension String  {

    
    // String length
    var length: Int { return self.characters.count }
    
    // 如果这个字符串是有效的双精度数字，分析一个字符串包含的 Optional Double值
    func toDouble() -> Double? {
        let scanner = Scanner(string: self)
        var double: Double = 0
        
        if scanner.scanDouble(&double) {
            return double
        }
        return nil
    }
    
    func isPureNum() -> Bool{
        let scan = Scanner(string: self)
        var val:Int32 = 0
        return scan.scanInt32(&val) && scan.isAtEnd
    }

    // Email validation
    var isEmail: Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
    }
    
    // Email validation
    var isPhoneNumber: Bool {
        let phoneRegex = "^((1[34578][0-9]{9})|((0\\d{2}-\\d{8})|(0\\d{3}-\\d{7,8})|(0\\d{10,11}))|(((400)-(\\d{3})-(\\d{4}))|((400)-(\\d{4})-(\\d{3}))|((400)-(\\d{5})-(\\d{2}))|(400\\d{7}))|(((800)-(\\d{3})-(\\d{4}))|((800)-(\\d{4})-(\\d{3}))|((800)-(\\d{5})-(\\d{2}))|(800\\d{7})))$"
        return NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: self)
    }
    
    var isTelPhoneNumber:Bool {
        let phoneRegex = "^(((0\\d{2}-\\d{8})|(0\\d{3}-\\d{7,8})|(0\\d{10,11}))|(((400)-(\\d{3})-(\\d{4}))|((400)-(\\d{4})-(\\d{3}))|((400)-(\\d{5})-(\\d{2}))|(400\\d{7}))|(((800)-(\\d{3})-(\\d{4}))|((800)-(\\d{4})-(\\d{3}))|((800)-(\\d{5})-(\\d{2}))|(800\\d{7})))$"
        return NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: self)
    }
    
    var isMobilePhone: Bool {
        let mobilePhone = "^(1[34578][0-9]{9})|((0\\d{2}-\\d{8})|(0\\d{3}-\\d{7,8})|(0\\d{10,11}))$"
        return NSPredicate(format: "SELF MATCHES %@", mobilePhone).evaluate(with: self)
    }
    
    // postCode validation
    var isPostCode: Bool {
        let phoneRegex = "^[0-8]\\d{5}(?!\\d)$"
        return NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: self)
    }
    
    // :returns: A float parsed from the string or nil if it cannot be parsed.
    func toFloat() -> Float? {
        
        let scanner = Scanner(string: self)
        var float: Float = 0
        if scanner.scanFloat(&float) {
            return float
        }
        return nil
        
    }
    
    // returns: A NSDate parsed from the string or nil if it cannot be parsed as a date.
    func toDate(format : String? = "yyyy-MM-dd") -> NSDate? {
        let text = self
        let dateFmt = DateFormatter()
        dateFmt.timeZone = NSTimeZone.default
        if let fmt = format {
            dateFmt.dateFormat = fmt
        }
        return dateFmt.date(from: text) as NSDate?
    }

    
    func queryDictionary() -> NSMutableDictionary {
        let queryArray = self.components(separatedBy: "&")
        let dic = NSMutableDictionary()
        for queryStr in queryArray {
            let queryArriArray = queryStr.components(separatedBy: "=")
            if queryArriArray.count == 2
            {
                let key = queryArriArray[0]
                let value = queryArriArray[1].removingPercentEncoding
                dic[key] = value
            }
        }
        return dic
    }
    
    public func stringByURLEncoding() -> String {
        return CFURLCreateStringByAddingPercentEscapes(
            nil,
            self as CFString!,
            nil,
            "!*'();:@&=+$,/?%#[]" as CFString!,CFStringBuiltInEncodings.UTF8.rawValue
            ) as String
    }
    
    var md5: String {
//        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
//        if let str = cString(using: String.Encoding.utf8) {
//            CC_MD5(str, CC_LONG(lengthOfBytes(using: String.Encoding.utf8)), &digest)
//        }
//        
//        return digest.reduce("") { result, byte in
//            result + String(format: "%02x", byte)
//        }
        return "asdfasd"
    }
}



